package cn.edu.fzu.homemaking.service.impl;

import cn.edu.fzu.homemaking.api.SysApi;
import cn.edu.fzu.homemaking.domain.entity.Area;
import cn.edu.fzu.homemaking.domain.entity.User;
import cn.edu.fzu.homemaking.domain.entity.UserAddress;
import cn.edu.fzu.homemaking.domain.vo.UserAddressVo;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.mapper.AddressMapper;
import cn.edu.fzu.homemaking.service.AddressService;
import cn.edu.fzu.homemaking.util.ResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author jiebin
 * @Date 2023/4/4
 */
@Service("addressService")
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private SysApi sysApi;

    @Override
    public void insert(Long userId, String name, Long areaId, String address, String phone, String email) {
        addressMapper.insert(userId, name ,areaId, address, phone, email);
    }

    @Override
    public void deleteById(Long id, User user) {
        UserAddress userAddress = addressMapper.selectById(id);
        if (!userAddress.getUserId().equals(user.getId())){
            throw new ServiceException("用户与该地址不匹配");
        }
        addressMapper.deleteById(id);
    }

    @Override
    public void updateById(Long id, String name, Long areaId, String address, String phone, String email, User user) {
        UserAddress userAddress = addressMapper.selectById(id);
        if (!userAddress.getUserId().equals(user.getId())){
            throw new ServiceException("用户与该地址不匹配");
        }
        addressMapper.updateById(id, name, areaId, address, phone, email);
    }

    @Override
    public UserAddressVo selectById(Long id) {
        UserAddress userAddress = addressMapper.selectById(id);
        Area area = ResultUtil.parseValue(sysApi.getAreaById(userAddress.getAreaId()), Area.class);
        UserAddressVo userAddressVo = new UserAddressVo();
        BeanUtils.copyProperties(userAddress, userAddressVo);
        userAddressVo.setArea(area);
        return userAddressVo;
    }

    @Override
    public List<UserAddressVo> list(Long userId) {
        List<UserAddress> userAddresses = addressMapper.list(userId);
        List<UserAddressVo> list = new ArrayList<>();
        for (UserAddress userAddress: userAddresses) {
            UserAddressVo userAddressVo = new UserAddressVo();
            BeanUtils.copyProperties(userAddress, userAddressVo);
            Area area = ResultUtil.parseValue(sysApi.getAreaById(userAddress.getAreaId()), Area.class);
            userAddressVo.setArea(area);
            list.add(userAddressVo);
        }
        return list;
    }
}
